package org.example;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class StaticResourceUtil {

    /**
     * 获取静态资源文件的绝对路径
     */
    public static String getAbsolutePath(String path) {
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\", "/") + path;
    }

    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int len = inputStream.available();
        while (len == 0) {
            len = inputStream.available();
        }
        outputStream.write(HttpProtocolUtil.getHttpHeader200().getBytes());

        long writeLen = 0;
        int bufSize = 1024;
        byte[] b = new byte[bufSize];
        while (writeLen < len) {
            if (writeLen + bufSize > len) {
                bufSize = (int) (len - writeLen);
                b = new byte[bufSize];
            }

            inputStream.read(b);
            outputStream.write(b);
            outputStream.flush();
            writeLen = writeLen + bufSize;
        }
    }

    public static void outputStaticResource(File file, OutputStream outputStream) throws IOException {
        outputStream.write(HttpProtocolUtil.getHttpHeader200().getBytes());

        Path path = Paths.get(file.getAbsolutePath());
        Files.copy(path, outputStream);
//        byte[] bytes = Files.readAllBytes(path);
//        outputStream.write(bytes);

        outputStream.flush();
        outputStream.close();
    }

}
